<template>
  <section class="mobile-user-info-page" :class="{'edit': isEdit}">
    <div class="body-box">
      <div class="avatar-box">
        <a v-if="!isEdit" class="edit-btn" @click="onEdit()">编辑</a>
        <p class="avatar-title">证件照</p>
        <div class="avatar-body">
            <div class="avatar-img-box">
              <van-uploader
                :disabled="!!form.studentPictureUrl"
                :after-read="afterRead"
                :max-count="1"
              >
                <img
                  v-if="form.studentPictureUrl"
                  :src="form.studentPictureUrl"
                  class="avatar-value"
                />
                <img v-else class="avatar-value" src="@/assets/images/user/userTouXiang.png" />
              </van-uploader>
              <img v-if="form.studentPictureUrl && isEdit" @click="deleteImg()" class="avatar-delete-icon" src="@/assets/images/mobile/close.png" />
          </div>
        </div>
      </div>
      <template v-if="!isEdit">
        <div class="border-line"></div>
        <div class="info-box">
          <p class="info-title">基本消息</p>
          <van-cell-group v-if="!isEdit">
            <template v-for="item in info[0]">
              <van-cell
                :key="item.val"
                v-if="item.val !== 'mobile' && item.val !== 'email'"
                :title="item.label"
                :value="userInfo[item.val] || '--'"
              />
            </template>
            <template v-for="item in info[1]">
              <van-cell
                :key="item.val"
                v-if="item.val !== 'mobile' && item.val !== 'email'"
                :title="item.label"
                :value="userInfo[item.val] || '--'"
              />
            </template>
          </van-cell-group>
        </div>
        <div class="border-line"></div>
        <div class="info-box">
          <p class="info-title">联系方式</p>
          <van-cell-group v-if="!isEdit">
            <template v-for="item in info[0]">
              <van-cell
                :key="item.val"
                v-if="item.val === 'mobile' || item.val === 'email'"
                :title="item.label"
                :value="userInfo[item.val] || '--'"
              />
            </template>
            <template v-for="item in info[1]">
              <van-cell
                :key="item.val"
                v-if="item.val === 'mobile' || item.val === 'email'"
                :title="item.label"
                :value="userInfo[item.val] || '--'"
              />
            </template>
          </van-cell-group>
        </div>
      </template>
      <template v-else>
        <p class="info-title">基本消息</p>
        <van-form ref="dataForm" :scroll-to-error="true" validate-trigger="onSubmit">
          <van-field
            class="form-item-input"
            v-model.trim="form.nickname"
            name="nickname"
            label="姓名"
            placeholder="请填写真实姓名，用于投递简历"
            maxlength="20"
            :rules="[{ required: true, message: '' }]"
          />
          <van-field class="form-item-right" name="identify" label="身份">
            <template #input>
              <van-radio-group v-model="form.identify" direction="horizontal">
                <van-radio
                  v-for="item in studentType"
                  :key="item.label"
                  :name="item.label"
                >
                  {{ item.label }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="liveCityMobile"
            :value="form.liveCityMobile"
            label="现居住城市"
            placeholder="请选择现居住城市"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowArea('liveCityMobile')"
          />
          <van-field class="form-item-right" name="sex" label="性别">
            <template #input>
              <van-radio-group v-model="form.sex" direction="horizontal">
                <van-radio name="女">女</van-radio>
                <van-radio name="男">男</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="clan"
            :value="form.clan"
            label="民族"
            placeholder="请选择民族"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowPicker('clan')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="datetimePicker"
            :value="form.birthday"
            label="出生日期"
            placeholder="请选择出生日期"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowTime('birthday')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="political"
            :value="form.political"
            label="政治面貌"
            placeholder="请选择政治面貌"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowPicker('political')"
          />
          <van-field
            class="form-item-input"
            readonly
            clickable
            name="nativePlaceMobile"
            :value="form.nativePlaceMobile"
            label="籍贯"
            placeholder="请选择籍贯"
            right-icon="arrow"
            :rules="[{ required: true, message: '' }]"
            @click="onShowArea('nativePlaceMobile')"
          />
          <p class="info-title">联系方式</p>
          <van-field
            class="form-item-input"
            v-model="form.mobile"
            type="tel"
            name="mobile"
            label="手机号码"
            placeholder="请输入手机号码"
            :rules="[{ required: true, message: '' }]"
            disabled
          />
          <van-field
            class="form-item-input"
            v-model="form.email"
            name="email"
            label="邮箱地址"
            placeholder="请输入邮箱地址"
            :rules="[{ message: '', validator: validataEmail }]"
          />
        </van-form>
      </template>
    </div>
    <div v-if="isEdit" class="btn-box">
      <van-button
        type="info"
        class="btn-item"
        @click="onSubmit()"
      >
        提交
      </van-button>
    </div>
    <van-popup v-model="showTimePicker" position="bottom">
      <van-datetime-picker
        v-model="timePickerValue"
        :type="timePickerType"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onTimeConfirm"
        @cancel="onTimeCancel"
      />
    </van-popup>
    <van-popup v-model="showArea" position="bottom">
      <van-cascader
        v-model="areaValue"
        title="请选择所在地区"
        :options="provinceAndCityData"
        :field-names="fieldNames"
        @close="showArea = false"
        @finish="onAreaConfirm"
      />
    </van-popup>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :default-index="pickerIndex"
        :columns="pickerColumns"
        :value-key="pickerKeyName"
        @confirm="onPickerConfirm"
        @cancel="onPickerCancel"
      />
    </van-popup>
  </section>
</template>

<script>
import Vue from 'vue'
import {  mapState } from "vuex";
import {
  getNationData,
  provinceAndCityData,
  getProvinceAndCityDataLabel,
  getProvinceAndCityDataValue,
  studentType,
} from "@/utils/frontDataDict";
import { deepClone } from "@/utils";
import moment from "moment";
import axios from "axios";
import { upUserInfo } from "@/request/api";
export default {
  // 组件名称
  name: "",
  // 组件参数 接收来自父组件的数据
  props: {
    userInfo: Object,
    info: Array,
  },
  // 局部注册的组件
  components: {

   },
  // 组件状态值
  data() {
    return {
      isEdit: false,
      studentType: studentType,
      politicalList: [
        "团员",
        "中共党员(含预备党员)",
        "民主党派",
        "无党派人士",
        "群众",
      ],
      provinceAndCityData,
      nationData: getNationData(),
      action:
        process.env.VUE_APP_BASE_API + "/app-api/student/web-student/upload",
      form: {
        nickname: "",
        sex: "",
        birthday: "",
        clan: "",
        political: "",
        liveCity: "",
        identify: "0", // 身份
        graduateTime: "", // 个人信息页面，毕业时间字段暂时废弃，仍保留
        mobile: "",
        email: "",
        nativePlace: "",
        studentPictureUrl: "",

        liveCityMobile: '',
        nativePlaceMobile: '',
      },

      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      timePickerValue: '',
      timePickerType: '',
      timePickerKey: '',
      timePickerFmt: '',
      showTimePicker: false,

      selectLiveCity: [],
      selectNativePlace: [],
      selectTargetCity: [],
      showAreaKey: '',
      showArea: false,
      fieldNames: {
        text: 'label',
        value: 'value',
      },
      areaValue: '',

      selectGrade: '',
      pickerIndex: 0,
      pickerKey: '',
      pickerKeyName: 'text',
      pickerColumns: [],
      showPicker: false,


    };
  },
  watch: {
    USER_INFO: function (newValue, oldValue) {
      let userInfo = deepClone(newValue);
      try {
        userInfo.liveCity &&
          (userInfo.liveCity = getProvinceAndCityDataValue(userInfo.liveCity));
        userInfo.nativePlace &&
          (userInfo.nativePlace = getProvinceAndCityDataValue(
            userInfo.nativePlace
          ));
      } catch {
        () => {};
      }
      console.log('userInfo', this.userInfo)
      this.form = userInfo;
      this.form.liveCityMobile = ''
      this.form.nativePlaceMobile = ''
    },
  },
  computed: {
    ...mapState(["USER_INFO"]),
  },
  created() {
  },
  // 组件方法
  methods: {
    onEdit() {
      this.form.liveCityMobile = this.userInfo.liveCity
      this.form.nativePlaceMobile = this.userInfo.nativePlace
      if (this.form.liveCity.length) {
        this.selectLiveCity = [
          {
            label: '',
            value: this.form.liveCity[0],
          },
          {
            label: '',
            value: this.form.liveCity[1],
          },
        ]
      }
      if (this.form.nativePlace.length) {
        this.selectNativePlace = [
          {
            label: '',
            value: this.form.nativePlace[0],
          },
          {
            label: '',
            value: this.form.nativePlace[1],
          },
        ]
      }
      console.log('this.form', this.form)
      this.isEdit = true
    },
    // 生日选择
    onShowTime(key) {
      if (this.isTillNowMobile && key === 'graduateTime') return
      this.timePickerValue = ''
      this.timePickerType = 'date'
      this.timePickerKey = key
      this.timePickerFmt = 'yyyy-MM-DD'
      this.minDate = new Date(1900, 0, 1)
      this.maxDate = new Date()
      if (this.form[key]) this.timePickerValue = new Date(this.form[key])
      if (key === 'intakeTime') {
        this.timePickerFmt = 'yyyy年MM月'
        if (this.form.graduateTime) {
          const time = this.form.graduateTime.replace('年', '-').replace('月', '')
          this.maxDate = new Date(time)
        }
        this.timePickerType = 'year-month'
      }
      if (key === 'graduateTime') {
        this.timePickerFmt = 'yyyy年MM月'
        // if (this.form.intakeTime) this.minDate = new Date(moment(this.form.intakeTime).format('yyyy-MM'))
        if (this.form.intakeTime) {
          const time = this.form.intakeTime.replace('年', '-').replace('月', '')
          this.minDate = new Date(time)
        }
        this.timePickerType = 'year-month'
      }
      this.showTimePicker = true
    },
    onTimeConfirm(e) {
      console.log('timePickerValue', this.timePickerValue)
      this.showTimePicker = false
      this.form[this.timePickerKey] = moment(e).format(this.timePickerFmt)
      console.log('onTimeConfirm', e)
    },
    onTimeCancel() {
      this.showTimePicker = false
      this.timePickerValue = ''
    },
    // 地区选择
    onShowArea(key) {
      this.showArea = true
      this.showAreaKey = key
      this.areaValue = ''
      if (key === 'liveCityMobile' && this.selectLiveCity.length) {
        this.areaValue = this.selectLiveCity[1].value
      }
      if (key === 'nativePlaceMobile' && this.selectNativePlace.length) {
        this.areaValue = this.selectNativePlace[1].value
      }
      // if (key === 'targetCityMobile' && this.selectTargetCity.length) {
      //   this.areaValue = this.selectTargetCity[1].value
      // }
    },
    onAreaConfirm({selectedOptions: arr}) {
      this.showArea = false
      // this.form.birthday = moment(e).format("yyyy-MM-DD")
      console.log('onAreaConfirm', arr)
      const ids = []
      arr.map(v => ids.push(v.value))
      if (this.showAreaKey == 'liveCityMobile') {
        this.selectLiveCity = arr
        this.form.liveCityMobile = arr[1].label
        this.form.liveCity = this.form.liveCityMobile
      }
      if (this.showAreaKey == 'nativePlaceMobile') {
        this.selectNativePlace = arr
        this.form.nativePlaceMobile = arr[0].label + arr[1].label
        this.form.nativePlace = this.form.nativePlaceMobile
      }
      // if (this.showAreaKey == 'targetCityMobile') {
      //   this.selectTargetCity = arr
      //   this.form.targetCityMobile = arr[1].label
      //   this.form.targetCity = ids
      // }
      console.log('this.areaValue', this.areaValue)
    },
    onChangeArea(picker, index, value) {
      console.log('onChangeArea', picker, index, value)
    },
    // 下拉选择
    onShowPicker(key) {
      this.pickerKeyName = 'text'
      let pickerIndex = 0
      console.log('this.nationData', this.nationData)
      if (key === 'clan') {
        this.nationData.map((v, i) => {
          if (v.label === this.form[key]) pickerIndex = i
        })
        this.pickerKeyName = 'label'
        this.pickerColumns = this.nationData
      }
      if (key === 'political') {
        this.politicalList.map((v, i) => {
          if (v === this.form[key]) pickerIndex = i
        })
        this.pickerColumns = this.politicalList
      }
      // if (key === 'educationalBackground') {
      //   this.educationalBackList.map((v, i) => {
      //     if (v === this.form[key]) pickerIndex = i
      //   })
      //   this.pickerColumns = this.educationalBackList
      // }
      // if (key === 'grade') {
      //   this.educationOptions.map((v, i) => {
      //     if (v.label === this.form[key]) pickerIndex = i
      //   })
      //   this.pickerColumns = this.educationOptions
      //   this.pickerKeyName = 'label'
      //   console.log('this.pickerKeyName', this.pickerKeyName)
      // }
      this.pickerIndex = pickerIndex
      this.pickerKey = key
      console.log('pickerIndex', pickerIndex)
      this.showPicker = true
    },
    onPickerConfirm(e) {
      console.log('e', e)
      if (this.pickerKey === 'clan') {
        this.form[this.pickerKey] = e.label
        this.selectGrade = e
      } else {
        this.form[this.pickerKey] = e
      }
      // if (this.pickerKey === 'educationalBackground') this.form.grade = ''
      this.onPickerCancel()
    },
    onPickerCancel() {
      this.showPicker = false
    },
    validataEmail(value) {
      return new Promise((resolve) => {
        let emailReg =
        /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
        if (value === "") {
          return resolve(false);;
        } else {
          if (emailReg.test(value)) {
            return resolve(true);
          } else {
            return resolve(false);;
          }
        }
      });
    },
    checkFile(file) {
      const typeSet = new Set(['image/jpeg', 'image/png', 'image/jpg'])
      const isFlag = typeSet.has(file.type);
      if (!isFlag) {
        this.$message.error("上传头像图片只能是 JPG、jpg、png 格式!");
      }
      return isFlag;
    },
    afterRead(files) {
      // 此时可以自行将文件上传至服务器
      console.log(files);
      const { file } = files
      const falg = this.checkFile(file);
      console.log('falg', falg)
      if (falg) this.uploadImg(files)
    },
    async uploadImg(files) {
      const res = await axios.post(this.action, files, {
        // 因为我们上传了图片,因此需要单独执行请求头的Content-Type
        headers: {
          // 表示上传的是文件,而不是普通的表单数据
          'Content-Type': 'multipart/form-data'
        }
      })
      this.form.studentPictureUrl = res.data.data || ''
    },
    deleteImg() {
      this.form.studentPictureUrl = ''
      this.$emit('deleteImg')
    },
    onSubmit() {
      this.$refs.dataForm.validate().then(() => {
        console.log('save')
        // this.$emit('submit')
        let parmas = JSON.parse(JSON.stringify(this.form));
        if(!parmas.liveCityMobile) {
          parmas.liveCity = getProvinceAndCityDataLabel(parmas.liveCity)
        } else {
          parmas.liveCity = parmas.liveCityMobile
        };
        if(!parmas.nativePlaceMobile) {
          parmas.nativePlace = getProvinceAndCityDataLabel(
            parmas.nativePlace,
            2
          );
        } else {
          parmas.nativePlace = parmas.nativePlaceMobile
        };
        parmas.studentName = parmas.nickname;
        upUserInfo(parmas).then((res) => {
          if (res.data) {
            this.$message({
              message: "提交成功",
              type: "success",
            });
            this.isEdit = false
            this.$emit('submit')
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
  },
  beforeDestroy() {
  }
};
</script>
<style lang="less">
.van-tabs__line {
  background-color: #4677B9;
}
.van-cascader__option--selected {
  color: #4677B9;
}
.van-button--info {
  border: 1px solid #4677B9;
  background-color: #4677B9;
}
</style>
<style lang="less" scoped>
.mobile-user-info-page {
  display: none;
  padding: 0 0.1rem;
  height: 100vh;
  overflow: auto;
  &.edit {
    padding-bottom: 0.75rem;
    .avatar-box {
      padding-bottom: 0;
    }
    .info-title {
      margin: 0.2rem 0 0.15rem;
    }
  }

  .border-line {
    display: block;
    width: 100%;
    height: 1px;
    background: #E6E6E6;
    opacity: 0.6;
  }

  ::v-deep .van-cell-group {
    &::after {
      border-width: 0;
    }
    .van-cell {
      padding: 0 0.05rem;
      line-height: 0.2rem;
      &::after {
        opacity: 0;
      }
      & + .van-cell {
        margin-top: 0.1rem;
      }
      .van-cell__title {
        font-size: 0.14rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383D;
        line-height: 0.2rem;
      }
      .van-cell__value {
        font-size: 0.14rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #9597A0;
        line-height: 0.2rem;
      }
    }
  }

  .edit-btn {
    position: absolute;
    top: 0.17rem;
    right: 0.1rem;
    font-size: 0.14rem;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #2F8EFE;
    line-height: 0.2rem;
  }

  .avatar-box {
    position: relative;
    padding: 0.15rem 0;
  }
  .avatar-title {
    font-size: 0.16rem;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #37383D;
    line-height: 0.22rem;
  }
  .avatar-body {
    display: flex;
    position: relative;
    margin-top: 0.1rem;
    align-items: center;
    justify-content: center;
  }
  .avatar-value {
    width: 1.2rem;
    height: 1.2rem;
    vertical-align: bottom;
    object-fit: cover;
  }
  .avatar-img-box {
    position: relative;
    ::v-deep .van-uploader__wrapper--disabled {
      opacity: 1;
    }
  }
  .avatar-delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    width: 0.2rem;
    height: 0.2rem;
  }

  .info-box {
    padding-bottom: 0.1rem;
  }
  .info-title {
    margin: 0.1rem 0 0.15rem;
    font-size: 0.16rem;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #37383D;
    line-height: 0.22rem;
  }


  ::v-deep .van-form {
    .van-cell {
      padding: 0.08rem  0;
      font-size: 0.14rem;
      &::after {
        right: auto;
        left: auto;
        width: 100%;
      }
      .van-field__label {
        margin-right: 0;
        width: 0.85rem;
        font-size: 0.14rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383D;
        line-height: 0.3rem;
      }
      .van-field__control  {
        min-height: 0.3rem;
      }
    }
    .van-radio-group--horizontal {
      justify-content: flex-end;
    }
    .van-radio--horizontal {
      margin-right: 0.1rem;
      min-width: 0.69rem;
    }
    .van-radio__label {
      line-height: 0.32rem;
    }
    .van-radio__icon,
    .van-checkbox__icon {
      font-size: 16px;
    }
    .form-item-input {
      &.disabled {
        background-color: #f1f1f1;
      }
      .van-field__body {
        border-radius: 0.02rem;
        border: 0.01rem solid #F0F0F0;
      }
      input {
        padding: 0.06rem 0.13rem;
        height: 0.32rem;
        font-size: 0.14rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        line-height: 0.2rem;
      }
      .van-icon {
        margin-right: 0.07rem;
      }
      &.van-field--error {
        .van-field__body {
          border-color: #ee0a24;
        }
      }
    }
    .form-item-right {
      .van-field__control,
      .van-radio--horizontal {
        justify-content: flex-end;
      }
    }
    .form-item-educational {
      .van-field__control--custom {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
      .form-item-input {
        padding: 0;
      }
      .van-radio--horizontal {
        min-width: 1.2rem;
      }
      &.van-field--error {
        .van-field__body {
          border-color: #ee0a24;
        }
      }
    }
    .form-item-educational-options {
      display: flex;
      margin-top: 0.14rem;
      flex-wrap: wrap;
      justify-content: flex-end;
      .van-radio__label {
        line-height: 0.2rem;
      }
    }
    .form-item-educational-tips {
      margin-top: 0.1rem;
      font-size: 0.12rem;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #B0B0B0;
      line-height: 0.17rem;
    }
    .form-item-times {
      display: flex;
      align-items: center;
    }
    .form-item-times-line {
      margin: 0 0.1rem;
    }
    .van-radio__icon--checked .van-icon {
      border-color: #4677B9;
      background-color: #4677B9;
    }
  }

  .btn-box {
    display: flex;
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1;
    padding: 0 0.15rem;
    width: 100%;
    height: 0.75rem;
    align-items: center;
    background-color: #fff;
  }
  .btn-item {
    flex: 1;
    height: 0.55rem;
    font-size: 0.18rem;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    line-height: 0.25rem;
    border-radius: 0.05rem;
  }
}
</style>
